route.test.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { describe, it, expect, beforeAll, afterAll } from "vitest";
  2. import fs from "node:fs/promises";
  3. import os from "node:os";
  4. import path from "node:path";
  5. import { GET as getYears } from "./route.js";
  6. let tmpRoot;
  7. beforeAll(async () => {
  8. tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "api-years-"));
  9. process.env.NAS_ROOT_PATH = tmpRoot;
  10. // tmpRoot/NL01/2024
  11. await fs.mkdir(path.join(tmpRoot, "NL01", "2024"), {
  12. recursive: true,
  13. });
  14. });
  15. afterAll(async () => {
  16. await fs.rm(tmpRoot, { recursive: true, force: true });
  17. });
  18. describe("GET /api/branches/[branch]/years", () => {
  19. it("returns years for a valid branch", async () => {
  20. const req = new Request("http://localhost/api/branches/NL01/years");
  21. // In Next.js 16, ctx.params is a Promise the framework would resolve.
  22. // In tests we simulate that.
  23. const ctx = {
  24. params: Promise.resolve({ branch: "NL01" }),
  25. };
  26. const res = await getYears(req, ctx);
  27. expect(res.status).toBe(200);
  28. const body = await res.json();
  29. expect(body).toEqual({
  30. branch: "NL01",
  31. years: ["2024"],
  32. });
  33. });
  34. it("returns 400 when branch param is missing", async () => {
  35. const req = new Request("http://localhost/api/branches/UNKNOWN/years");
  36. const ctx = {
  37. params: Promise.resolve({}), // no branch
  38. };
  39. const res = await getYears(req, ctx);
  40. expect(res.status).toBe(400);
  41. const body = await res.json();
  42. expect(body.error).toBe("branch Parameter fehlt");
  43. });
  44. it("returns 500 when NAS_ROOT_PATH is invalid", async () => {
  45. const originalRoot = process.env.NAS_ROOT_PATH;
  46. process.env.NAS_ROOT_PATH = path.join(tmpRoot, "does-not-exist");
  47. const req = new Request("http://localhost/api/branches/NL01/years");
  48. const ctx = {
  49. params: Promise.resolve({ branch: "NL01" }),
  50. };
  51. const res = await getYears(req, ctx);
  52. expect(res.status).toBe(500);
  53. const body = await res.json();
  54. expect(body.error).toContain("Fehler beim Lesen der Jahre:");
  55. process.env.NAS_ROOT_PATH = originalRoot;
  56. });
  57. });